package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.nursing.domain.dto.ReservationDto;
import com.zzyl.nursing.domain.pojo.Reservation;
import com.zzyl.nursing.mapper.ReservationMapper;
import com.zzyl.nursing.service.IReservationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 预约信息Service业务层处理
 */
@Service
public class ReservationServiceImpl extends ServiceImpl<ReservationMapper, Reservation> implements IReservationService {
    @Autowired
    private ReservationMapper reservationMapper;


    /**
     * 2.1 查询当天取消预约数量
     */
    @Override
    public Long getAllCancellerdCount() {
        long time = System.currentTimeMillis();
        LocalDateTime ldt = LocalDateTimeUtil.of(time);
        LocalDateTime startTime = ldt.toLocalDate().atStartOfDay();
        LocalDateTime endTime = startTime.plusDays(1);
        Long currentUserId = UserThreadLocal.getValue();
        return reservationMapper.getAllCancellerdCount(currentUserId, startTime, endTime);
    }

//    /**
//     * 2.2 查询每个时间段剩余预约次数
//     */
//    @Override
//    public CountByTimeVo getReservationCount(long time) {
//        return reservationMapper.getReservationCount(time);
//    }

    /**
     * 2.3 新增预约
     */
    @Override
    public void add(ReservationDto reservationDto) {
        Reservation reservation = BeanUtil.toBean(reservationDto, Reservation.class);
        reservation.setCreateTime(DateTime.now());
        reservation.setUpdateTime(DateTime.now());
        reservation.setCreateBy(String.valueOf(UserThreadLocal.getValue()));
        reservation.setUpdateBy(String.valueOf(UserThreadLocal.getValue()));
        reservation.setStatus(0);
        this.save(reservation);
    }

    /**
     * 2.4分页查询预约
     */
    @Override
    public List<Reservation> selectReservationList() {
        List<Reservation> list = this.list();
        return list;
    }

    /**
     * 2.5取消预约
     */
    @Override
    public void cancel(Long id) {
        //判断当前取消预约次数
        Long allCancellerdCount = this.getAllCancellerdCount();
        if (allCancellerdCount >= 3) {
            throw new RuntimeException("取消预约次数已达上限");
        }
        this.lambdaUpdate()
                .eq(Reservation::getId, id)
                .set(Reservation::getStatus, 2)
                .update();
    }


}
